package com.hualongdata.util;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * java 8 time utils
 * Created by yangbajing(yangbajing@gmail.com) on 2016-09-9.
 */
public class TimeUtils {
    public static final ZoneOffset ZONE_OFFSET = ZoneOffset.of("+08");

    private static final DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static final DateTimeFormatter localTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    public static long nowSeconds() {
        return nowMillis() / 1000;
    }

    public static long nowMillis() {
        return System.currentTimeMillis();
    }

    public static LocalDate toLocalDate(Date date) {
        return toLocalDateTime(date).toLocalDate();
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    public static LocalDate parseLocalDate(String date) {
        return LocalDate.parse(date);
    }

    public static String formatLocalDateTime(LocalDateTime localDateTime) {
        return localDateTime.format(localDateTimeFormatter);
    }

    public static String formatLocalDate(LocalDate localDate) {
        return localDate.format(localDateFormatter);
    }

    public static String formatLocalTime(LocalTime localTime) {
        return localTime.format(localTimeFormatter);
    }

    public static Date toDate(LocalDate ldt) {
        return new Date(ldt.atStartOfDay().toInstant(ZONE_OFFSET).toEpochMilli());
    }

    public static Date toDate(LocalDateTime ldt) {
        return new Date(ldt.toInstant(ZONE_OFFSET).toEpochMilli());
    }

    public static String formatDate(Date date) {
        return formatDate(new java.sql.Date(date.getTime()));
    }

    public static String formatDate(java.sql.Date date) {
        return formatLocalDate(date.toLocalDate());
    }

    public static String formatTime(java.sql.Time time) {
        return formatLocalTime(time.toLocalTime());
    }

    public static String formatTimestamp(java.sql.Timestamp timestamp) {
        return formatLocalDateTime(timestamp.toLocalDateTime());
    }
}